var dialog = {
    configs: {
        title: "div.title",
        head: "div.dialog_header",
        body: "div.dialog_body",
        foot: "div.dialog_footer",
        content: "div.dialog_content",
        button: "div.dialog_footer .dialog_button",
        close: "div.dialog_close",
        frame: "iframe.dialog_iframe",
        dialog: "div.dialog_box",
        loading: "div.dialog_loading"
    },
    options: {
        id: 'dialog', //弹出框的ID,可选,默认将自动生成
        title: '标题', //标题,可选,如果为空则隐藏标题栏
        content: '', //HTML内容
        width: 'auto', //内容宽度,默认为自适应宽度
        height: 'auto', //内容高度,默认为自适应高度
        x: "center", //弹出框X轴位置,默认为水平居中center,可选left,center,right
        y: "middle", //弹出框Y轴位置,默认为垂直居中middle,可选top,middle,bottom
        refix: true, //窗口变更是否重定位位置,只有当x或y为非数字定从头再来时才有效
        fixed: false, //是否为固定模式,表现为滚动条滚动时弹出层是否滚动
        time: 0, //是否自动关闭弹出框,为0时不自动关闭,单位毫秒
        lock: false, //是否锁定背景元素,锁定后背景将不能再操作,但仍然可以看见
        mask: false, //是否显示遮罩层,使用遮罩将淡化背景,使用视觉主体在弹出框,如果此项为true,则lock必定为true
        drag: true, //是否可以拖动弹出层
        range: false, //拖动时是否锁定在窗口可视区域内
        follow: null, //是否为追随模式,这里传入一个DOM元素,如#test或#test h3
        remove: false, //是否移除其它已有的弹出层
        style: '', //弹出层样式,配合CSS可用作一些特殊效果,如图片展示等
        buttons: [], //弹出层按钮集合
        close: null, //当弹出层关闭时执行的事件
        open: null   //当弹出层加载后执行的事s件
    },
    init: function(options, configs) {
        this.opts = $.extend(this.options, options || {});
        this.conf = $.extend(this.configs, configs || {});
        return register('dialog');
    },
    load: function(options, configs) {
        this.opts = $.extend({}, this.options, options || {});
        this.conf = $.extend({}, this.configs, configs || {});
        this.data = {};
        this.opts.width += isNaN(this.opts.width) ? "" : "px";
        this.opts.height += isNaN(this.opts.height) ? "" : "px";
        if (this.opts.id == 'dialog' || this.opts.id == '') {
            this.opts.id = 'dialog' + Math.floor(Math.random() * 10000 + 1);
        }
        //移除其它所有的dialog
        if (this.opts.remove) {
            $(".dialog_mask,.dialog_box").remove();
        }
        var lockdiv = '';
        if (this.opts.lock || this.opts.mask) {
            this.opts.lock = this.opts.mask ? true : this.opts.lock;
            lockdiv = this.opts.lock ? '<div class="' + (this.opts.lock ? 'dialog_lock' : '') + ' ' + (this.opts.mask ? 'dialog_mask' : '') + '"></div>' : '';
        } else {
            lockdiv = '';
        }

        if ($('#' + this.opts.id).length > 0) {
            //如果对话框缓存为true
            if (this.opts.cache) {
                if (lockdiv && !$('#' + this.opts.id).prev().hasClass("dialog_lock")) {
                    $('#' + this.opts.id).before(lockdiv);
                }
                var _this = this;
                $('#' + this.opts.id).show(0, function() {
                    if (_this.opts.open)
                        _this.opts.open(_this);
                }).click();
                this.dialog = $('#' + this.opts.id);
                this._getDom();
                this._setData();
                this._resizeDialog();
                if (this.opts.lock) {
                    $(".dialog_lock").height(this.data.ch);
                }
                return this;
            }
            $('#' + this.opts.id).prev(".dialog_lock").remove();
            $('#' + this.opts.id).remove();
        }
        if ($('#' + this.opts.id).length == 0) {
            var _html = [];
            _html.push(lockdiv);
            _html.push('<div class="dialog_box ' + this.opts.style + '" id="' + this.opts.id + '" style="display:none;height:auto;">');
            _html.push('    <div class="dialog_layer">');
            _html.push('    <div class="dialog_header" ' + (this.opts.title == '' ? 'style="display:none;"' : '') + '>');
            _html.push('        <h3 class="dialog_title">' + this.opts.title + '</h3>');
            _html.push('        <div class="dialog_close">×</div>');
            _html.push('    </div>');
            _html.push('    <div class="dialog_body">');
            _html.push('        <div class="dialog_content" style="height:' + this.opts.height + ';width:' + this.opts.width + ';">' + this.opts.content + '</div>');
            _html.push('    </div>');
            _html.push('    <div class="dialog_footer" style="display:none;"></div>');
            _html.push('</div>');
            _html.push('</div>');
            this.data.ie6 = $.browser.msie && /MSIE 6\.0/i.test(window.navigator.userAgent);
            $(_html.join("")).appendTo(document.body);
        }
        this.dialog = $('#' + this.opts.id);
        this._getDom();
        this.buttons(this.opts.buttons);
        this._setData();
        this._getAxis();
        this._regEvent();
        this._showDialog();
        return this;
    },
    index: function() {
        if (this.dialog.css('z-index') != 9999) {
            var d;
            $(".dialog_box").each(function() {
                d = $(this);
                d.css('z-index', d.css('z-index') - 1);
            });
            this.dialog.css('z-index', 9999);
        }
        return this;
    },
    drag: function() {
        var _this = this;
        var d = $(document);
        _this.dom.head.css("cursor", "move");
        _this.dom.head.bind('mousedown', function(e) {
            var e = e || window.event;
            if (e.target != this)
                return false;
            //重置z-index的值,置为最前
            _this.index();
            var positionX = e.clientX - _this.dialog.offset().left;
            var positionY = e.clientY - _this.dialog.offset().top;
            d.mousemove(function(e) {
                var left = e.clientX - positionX;
                var top = e.clientY - positionY;
                if (_this.opts.range) {
                    var w = $(window);
                    var mintop = w.scrollTop();
                    var minleft = w.scrollLeft();
                    //防止顶部和左侧消失
                    left = _this.opts.range && left < minleft ? minleft : left;
                    top = _this.opts.range && top < mintop ? mintop : top;
                    var range_l = w.width() - _this.dialog.outerWidth() + minleft;
                    var range_t = w.height() - _this.dialog.outerHeight() + mintop;
                    //防止底部和右侧消失
                    left = _this.opts.range && left >= range_l ? range_l : left;
                    top = _this.opts.range && top >= range_t ? range_t : top;
                }
                _this.dialog.css({
                    position: 'absolute',
                    left: left,
                    top: top
                });
            });
            d.mouseup(function() {
                d.unbind('mousemove');
                d.unbind('mouseup');
                this.releaseCapture && this.releaseCapture();
            });
            this.setCapture && this.setCapture();
            return false;
        });
    },
    debug: function() {
        console.log(this);
        return this;
    },
    close: function(callback) {
        if (this.opts == null)
            return false;
        if (callback != undefined && typeof callback == 'function')
            this.opts.close = callback;
        if (this.opts.close && typeof this.opts.close == 'function') {
            this.opts.close(this);
        }
        this.dialog.prev(".dialog_lock").remove();
        if (this.opts.cache) {
            this.dialog.hide();
        } else {
            this.dialog.unbind('click');
            this.dom.head.unbind('mousedown');
            if (this.data.timeout != undefined) {
                clearTimeout(this.data.timeout);
            }
            this.dialog.remove();
            this.data = null;
            this.conf = null;
            this.opts = null;
        }
    },
    buttons: function(_buttons) {
        var _this = this;
        if (_buttons && _buttons != [] && _buttons != {}) {
            if (_buttons.constructor == Object) {
                _buttons = [_buttons];
            }
            if (_buttons.length > 0) {
                $.each(_buttons, function(i, item) {
                    if (item && item.constructor == String) {
                        var _title = item;
                        item = {};
                        item.title = _title;
                        item.classType = 'cancel';
                        item.type = '';
                        item.classname = 'btn_w_s';
                        item.icon = '';
                    }
                    item.type = !item.type ? 'button' : item.type;
                    var btn = $("<button type='" + item.type + "' title='" + item.title + "' class='btn " + item.classname + "'><span>" + (item.icon ? "<b class='icon " + item.icon + "'></b>" : '') + "<em>" + item.title + "</em></span></button>");
                    btn.appendTo(_this.conf.foot).bind('click', function() {
                        if (item.callback && item.callback.constructor == Function) {
                            item.callback(_this);
                        }
                        if (item.close) {
                            _this.close();
                        }
                    });
                    if (item.type == 'main' || item.type == 'submit') {
                        btn.focus();
                    }
                    _this.dom.foot.show();
                });
            }
        }
        return _this;
    },
    resize: function(params, duration, easing, callback) {
        params = params || {};
        if (params.width || params.height) {
            params.width = params.width ? params.width : this.data.dw;
            params.height = params.height ? params.height : this.data.dh;
            var seconds = typeof duration == 'function' ? 'normal' : duration;
            this.dom.content.stop().animate(params, seconds);
        } else {
            this._setData();
            this._getAxis();
            params.left = params.left ? params.left : this.opts.left;
            params.top = params.top ? params.top : this.opts.top;
            this.dialog.stop().animate(params, duration, easing, callback);
        }
        return this;
    },
    timer: function(millisecond, callback) {
        var _this = this;
        this.data.time = millisecond;
        if (callback != undefined && typeof callback == 'function')
            this.opts.close = callback;
        if (this.data.timeout != undefined) {
            clearTimeout(this.data.timeout);
        }
        this.data.timeout = setTimeout(function() {
            _this.close();
        }, this.data.time);
    },
    update: function(html) {
        $(this.dom.content).append(html);
        this.resize({});
        return this;
    },
    _regEvent: function() {
        var _this = this;
        //点击置顶事件
        $(this.dialog).bind("click", function() {
            _this.index();
        });
        //拖动事件
        if (this.opts.drag) {
            _this.drag();
        }
        ;
        //自动关闭
        if (this.opts.time > 0) {
            this.timer(this.opts.time);
        }
        ;
        //窗口事件改变时是否自动修复弹出框位置
        if (this.opts.refix && this.opts.follow == null && (isNaN(this.opts.x) || isNaN(this.opts.y))) {
            $(window).resize(function() {
                if (_this.conf && _this.data) {
                    _this.data.ww = $(this).width();
                    _this.data.wh = $(this).height();
                    _this._resizeDialog();
                }
            });
        }
        ;
        //点击关闭事件
        $(this.dom.close).click(function() {
            _this.close();
        });
        //点击ESC事件
        $(document).bind('keydown', function(e) {
            if (e.keyCode == 27 && _this.dialog.css('z-index') == 9999) {
                _this.close();
            }
        });
        return this;
    },
    _showDialog: function() {
        var _this = this;
        this.data.position = this.opts.fixed ? "fixed" : "absolute";
        this.dialog.css({
            left: this.opts.left + 'px',
            top: this.opts.top + 'px',
            position: this.data.position,
            "z-index": this.data.zindex
        });
        if (this.data.ie6) {
            //防ie6跳动
            $("body").css("background-attachment", "fixed").css("background-image", "url(about:blank)");
            this.dialog.css({
                position: 'absolute',
                width: this.dialog.width() + "px"
            });
        }
        if (this.opts.lock) {
            $(".dialog_lock").height(this.data.ch);
        }
        this.dialog.show(0, function() {
            if (_this.opts.open)
                _this.opts.open(_this);
        }).click();
        return this;
    },
    _resizeDialog: function() {
        if (this.opts != null) {
            this._getAxis();
            this.dialog.stop().animate({
                left: this.opts.left,
                top: this.opts.top
            }, 300);
        }
    },
    _getDom: function() {
        this.dom = {
            title: $(this.conf.title, this.dialog),
            head: $(this.conf.head, this.dialog),
            body: $(this.conf.body, this.dialog),
            foot: $(this.conf.foot, this.dialog),
            content: $(this.conf.content, this.dialog),
            close: $(this.conf.close, this.dialog),
            loading: $(this.conf.loading, this.dialog),
            dialog: $(this.conf.dialog, this.dialog)
        }
        return this;
    },
    _getAxis: function() {
        var x = 0;
        var y = 0;
        if (this.opts.follow) {
            //当为跟随对象时强制转换fixed为false
            this.opts.fixed = false;
            var obj = this._getPosition($(this.opts.follow)[0]);
            x = obj.left;
            y = obj.top + obj.height;
            fx = this.data.cw - this.data.dw;
            fy = obj.top - this.data.dh;
            x = x > fx ? fx - 35 : x;
            y = (fy > this.data.dh && y > fy) ? fy : y;
        } else {
            x = this.opts.x;
            y = this.opts.y;
            if (x == 'left') {
                x = 0;
            } else if (x == "center" || x == "middle") {
                x = this.data.ww / 2 - this.data.dw / 2 + $(window).scrollLeft();
                x += this.opts.fixed ? 0 : $(window).scrollLeft();
            } else if (x == 'right') {
                x = this.data.ww - this.data.dw;
            } else {
                x = x;
            }
            if (y == 'top') {
                y = 0;
            } else if (y == "center" || y == "middle") {
                y = this.data.wh / 2 - this.data.dh / 2;
                y += this.opts.fixed ? 0 : $(window).scrollTop();
            } else if (y == 'bottom') {
                y = this.data.wh - this.data.dh;
            } else {
                y = y;
            }
            x = this._stripPx(x);
            y = this._stripPx(y);
        }
        this.opts.left = x;
        this.opts.top = y;
        return this;
    },
    _getPosition: function(e) {
        var top = 0;
        var left = 0;
        var width = 0;
        var height = 0;
        if (e != undefined) {
            top = e.offsetTop;
            left = e.offsetLeft;
            width = e.offsetWidth;
            height = e.offsetHeight;
            while (e = e.offsetParent) {
                top += e.offsetTop;
                left += e.offsetLeft;
            }
        }
        return {
            top: top,
            left: left,
            width: width,
            height: height
        }
    },
    _stripPx: function(u) {
        //处理px单位
        return parseInt(String(u).split("p")[0]);
    },
    _setData: function() {
        //获取客户端屏幕尺寸
        this.data.cw = document.body.clientWidth;
        this.data.ch = document.body.clientHeight;
        //获取弹出层尺寸
        this.data.dw = this.dialog.outerWidth();
        this.data.dh = this.dialog.outerHeight();
        //获取可视窗口尺寸
        this.data.ww = $(window).width();
        this.data.wh = $(window).height();
        this.data.mh = $(document.body)[0].offsetHeight < this.data.wh ? this.data.wh : $(document.body)[0].offsetHeight;
        this.data.zindex = 9998;
        return this;
    }
};

jQuery.dialog = function(options) {
    return dialog.init().load(options);
};
jQuery.dialog.alert = function(content, options) {
    $.dialog.warning(content, options);
}
//警告对话框(内容,对话框选项)
jQuery.dialog.warning = function(content, options) {
    var _this = dialog.init();
    options = options || {};
    var opts = {
        id: 'warning',
        title: '温馨提示',
        width: 300,
        y: 150,
        fixed: true,
        content: "<div class='d_layer d_alert clear'><dl><dt><span class='img img_warning_b'>&nbsp;</span></dt><dd>" + content + "</dd></dl></div>",
        mask: true,
        buttons: {
            title: '确定',
            type: 'main',
            close: true,
            callback: options.callback || $.noop
        }
    };
    $.extend(opts, options);
    _this.load(opts);
    return _this;
};
//询问对话框大(内容,对话框选项)
jQuery.dialog.confirm = function(content, options) {
    var _this = dialog.init();
    options = options || {};
    var opts = {
        id: 'confirm',
        title: '温馨提示',
        width: 300,
        y: 150,
        fixed: true,
        content: "<div class='d_layer d_confirm clear'><dl><dt><span class='img img_ask_b'>&nbsp;</span></dt><dd>" + content + "</dd></dl></div>",
        mask: true,
        buttons: [{
                title: '确定',
                type: 'main',
                icon: 'icon-ok',
                close: true,
                callback: options.yes || $.noop
            }, {
                title: '取消',
                type: 'cancel',
                icon: 'icon-remove',
                classname: 'btn_w_s',
                close: true,
                callback: options.no || $.noop
            }
        ]
    };
    $.extend(opts, options);
    _this.load(opts);
    return _this;
};
//询问对话框小(内容,对话框选项)
jQuery.dialog.ask = function(content, options) {
    var _this = dialog.init();
    options = options || {};
    var opts = {
        id: 'ask',
        title: '',
        buttons: [{
                title: '确定',
                type: 'main',
                icon: 'icon-ok',
                close: true,
                callback: options.yes || $.noop
            }, {
                title: '取消',
                type: 'cancel',
                icon: 'icon-remove',
                classname: 'btn_w_s',
                close: true,
                callback: options.no || $.noop
            }],
        content: "<div class='d_layer d_ask clear'><dl><dt><span class='img img_ask_m'>&nbsp;</span></dt><dd>" + content + "</dd></dl></div>"
    };
    $.extend(opts, options);
    _this.load(opts);
    return _this;
};
//AJAX读取内容(标题,对话框选项,AJAX选项,状态标签对象)
jQuery.dialog.ajax = function(title, options, params, obj) {
    options = options || {};
    options.id = 'dialog' + options.id;
    //如果缓存了数据就直接返回了
    if (options.cache) {
        if ($("#" + options.id).size() > 0) {
            var _this = dialog.init();
            var opts = {};
            opts.mask = false;
            opts.lock = true;
            opts.fixed = true;
            $.extend(opts, options);
            _this.load(opts);
            $(obj).removeAttr("posted");
            return true;
        }
    }
    $("b.icon", obj).addClass("icon-loading");
    $("#loading").show();
    var ajaxparams = $.extend({
        type: 'GET',
        dataType: 'html',
        cache: false
    }, params);
    $.extend(ajaxparams, {
        success: function(ret) {
            if (ret == '' || ret == 'error') {
                $.dialog.alert("加载内容失败！请重试！");
            } else if (ret.substr(0, 8) == '{"code":') {
                eval("var ret=" + ret);
                if (ret.content != undefined) {
                    $.dialog.alert(ret.content);
                } else {
                    $.dialog.alert(ret);
                }
            } else {
                var _this = dialog.init();
                var opts = {};
                opts.title = title;
                opts.mask = false;
                opts.lock = true;
                opts.fixed = true;
                opts.content = ret;
                $.extend(opts, options);
                _this.load(opts);
                if (params.success) {
                    params.success(ret, _this);
                }
            }
        },
        error: function(ret) {
            if (params.error) {
                params.error(ret);
            } else {
                $.dialog.alert($(ret.responseText).text());
            }
        },
        complete: function(ret) {
            $("b.icon", obj).removeClass("icon-loading");
            $("#loading").hide();
            $(obj).removeAttr("posted");
        }
    });
    $.ajax(ajaxparams);
};
jQuery.dialog.iframe = function(url, options) {
    return dialog.init().load(options).update($('<iframe />', {
        "class": "Iframe_Content",
        "src": url,
        "css": {
            "border": "none",
            "width": "100%",
            "height": '100%'
        },
        "frameborder": "0"
    }).clone());
};
jQuery.dialog.suggest = function(content, options) {
    var _this = dialog.init();
    options = options || {};
    var opts = {
        title: '',
        content: content,
        mask: false,
        width: 230,
        close: null,
        style: 'suggest'
    };
    $.extend(opts, options);
    _this.load(opts);
    var bTop = $(document).scrollTop();
    _this.dialog.stop(true, true).css({
        "top": ($(window).height() - _this.data.dh) / 4 * 3 + bTop,
        "opacity": 0.1
    }).animate({
        "opacity": 1,
        "top": _this.dialog.position().top - 30
    }, 800, function() {
        _this.dialog.delay(1200).animate({
            "opacity": 0.1,
            "top": _this.dialog.position().top - 30
        }, 1200, function() {
            _this.close();
        });
    });
    return _this;
};

jQuery.fn.dialog = function(options) {
    options = $.extend({}, {
        content: $(this).html()
    }, options || {});
    return dialog.init().load(options);
};
var register = function(module) {
    var _this = this;
    var _func = function(module) {
        if (module && _this[module]) {
            for (var i in _this[module]) {
                this[i] = _this[module][i];
            }
        }
        return this;
    };
    return new _func(module);
}